import { Component, Input, OnInit } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-bpm-tool',
  templateUrl: './bpm.tool.component.html'
})
export class BpmToolComponent implements OnInit {
  // 人员选择数据
  userIDs: string;
  userNames: string;

  bs: any = null;
  @Input()
  get bpmServer() {
    return this.bs;
  }
  set bpmServer(value) {
    this.bs = value;
  }

  constructor(
    public route: ActivatedRoute,
    private modalService: NzModalService,
    private msg: NzMessageService) {
  }

  ngOnInit() {
    // 浏览器关闭监听
    window.onbeforeunload = () => {
      // tslint:disable-next-line: deprecation
      const e: any = window.event;
      e.returnValue = ('请确认已保存，是否离开？');
      return e;
    };
  }

  close() {
    window.close();
  }

  save() {
    this.bs.processSave(() => {
      this.optUrl();
      this.msg.info('保存成功！');
    });
  }

  getSignTask() {
    this.bs.getSignTask(
      () => {
        this.modalService.confirm({
          nzTitle: '系统提示',
          nzContent: '提交后将结束流程，您确认吗？',
          nzOnOk: () => {
            this.send();
          }
        });
        return false;
      },
      () => {
        this.findWork();
      });
  }

  send() {
    // 处理自由流程下的人员选择
    if (this.bs.info.type === '3' && this.bs.freeTask !== 'U9') {
      const us = [];
      if (this.userIDs && this.userIDs.length > 0) {
        const ids = this.userIDs.split(',');
        const names = this.userNames.split(',');
        let index = 0;
        ids.forEach(id => {
          us.push({
            userId: id, userName: names[index], superAdmin: false, userSelected: true
          });
          index++;
        });
      }
      this.bs.result.tasks[0].users = us;
    }
    this.bs.send(() => {
      this.findWork();
    });
  }

  disposal() {
    this.modalService.confirm({
      nzTitle: '系统提示',
      nzContent: '您确认退件吗？',
      nzOnOk: () => {
        this.bs.disposal(() => {
          this.findWork();
        });
      }
    });
  }

  easter() {
    this.modalService.confirm({
      nzTitle: '系统提示',
      nzContent: '您确认激活吗？',
      nzOnOk: () => {
        this.bs.easter(() => {
          this.findWork();
        });
      }
    });
  }

  getBackTask() {
    this.bs.getBackTask(() => {
      this.findWork();
    });
  }

  revokeTask() {
    this.modalService.confirm({
      nzTitle: '系统提示',
      nzContent: '您确认撤回吗？',
      nzOnOk: () => {
        this.bs.revokeTask(() => {
          this.findWork();
        });
      }
    });
  }

  private findWork() {
    this.bs.findWork();
    this.optUrl();
  }

  private optUrl() {
    const href = window.location.href;
    if (href.indexOf('&id=') < 0) {
      window.location.href = href + '&id=' + this.bs.dataKey;
    }
  }
}
